<template>
  <div class="birthday-user-list">
    <!--    <el-card style="margin-bottom: 20px;" shadow="never">-->
    <!--      asdf-->
    <!--    </el-card>-->

    <el-card style="margin-bottom: 20px;" shadow="never">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="addBirthdayUser">添加生日人员</el-button>
      </div>
      <el-table
        :data="list"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="years" label="年月" align="center">
          <template v-slot="{ row }">
            {{ timeFormat(row.years, 'YYYY.MM') }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="人员" align="center">
          <template v-slot="{ row }">
            <el-popover
              placement="top-start"
              title="人员"
              width="200"
              trigger="hover"
            >
              <template #reference>
                <el-button type="text">查看</el-button>
              </template>
              <el-tag
                v-for="(item, index) in JSON.parse(row.name)"
                :key="index"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ item }}
              </el-tag>
            </el-popover>

          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" @click="edit(row)">编 辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <Pagination
          v-if="total"
          style="margin-top: 0; padding-bottom: 0;"
          :total="total"
          :limit="params.paginate"
          :page="params.page"
          @pagination="pagination"
        />
      </div>
    </el-card>
    <el-dialog
      :visible.sync="show"
      :title="user.id ? '编辑生日人员' : '添加生日人员'"
      width="350px"
    >
      <div class="input-box">
        <div
          class="field"
        >
          <span class="title" style="min-width: 60px;">年 月：</span>
          <el-date-picker
            v-model="years"
            type="month"
            placeholder="选择年月"
          />
        </div>

        <div
          v-for="(item, index) in user.users"
          :key="index"
          class="field"
        >
          <span class="title" style="min-width: 60px;">人员{{ index + 1 }}：</span>
          <el-input v-model="user.users[index]" style="width: 300px;" placeholder="请输入人员姓名" />
          <el-button
            icon="el-icon-delete"
            type="danger"
            circle
            style="margin-left: 10px;"
            @click="remove(index)"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="user.users.push('')">添 加</el-button>
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getList, createCurrentMonthBirthdayUser, updateCurrentMonthBirthdayUser } from '@/api/birth'
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
export default {
  name: '',
  components: { Pagination },
  data() {
    return {
      list: [],
      params: {
        years: null,
        paginate: 10,
        page: 1
      },
      years: null,
      total: 0,
      user: {
        id: null,
        users: ['']
      },
      show: false
    }
  },
  created() {
    this.getBirthdayList()
  },
  methods: {
    async getBirthdayList() {
      try {
        const res = await getList(this.params)
        console.log('res --------->', res)
        this.list = res.data.data
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      }
    },

    addBirthdayUser() {
      this.user.users = ['']
      this.years = null
      this.show = true
    },

    async createCurrentMonthBirthdayUserFetch() {
      try {
        await createCurrentMonthBirthdayUser({
          name: JSON.stringify(this.user.users),
          years: this.timeFormat(this.years, 'YYYYMM', 'YYYY-MM')
        })
        this.$message.success('创建成功')
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '创建失败')
      }
    },

    timeFormat(time, format = 'YYYY-MM-DD', f = 'YYYYMM') {
      const ft = dayjs(time, { format: f })
      if (!ft.isValid()) return null
      return ft.format(format)
    },

    pagination(e) {
      this.params.page = e.page
      this.params.paginate = e.limit
      this.getBirthdayList()
    },

    async onConfirm() {
      try {
        const res = await this.validate()
        if (!res) return this.$message.error('请将信息填写完整')
        if (this.user.id) {
          await this.updateCurrentMonthBirthdayUser()
        } else { await this.createCurrentMonthBirthdayUserFetch() }
        this.show = false
        this.refresh()
      } catch (error) {
        throw new Error(error.message)
      }
    },

    refresh() {
      this.getBirthdayList()
    },

    validate() {
      return new Promise(resolve => {
        const index = this.user.users.findIndex(item => item === '')
        if (index !== -1) resolve(false)
        resolve(true)
      })
    },

    remove(index) {
      // if (this.user.users.length === 1) return this.$message.error('至少添加一人')
      this.user.users.splice(index, 1)
    },

    edit(row) {
      console.log('row --------->', row)
      this.user.users = JSON.parse(row.name)
      this.user.id = row.id
      this.years = this.timeFormat(row.years, 'YYYY-MM', 'YYYYMM')
      this.show = true
    },

    async updateCurrentMonthBirthdayUser() {
      try {
        const res = await updateCurrentMonthBirthdayUser({
          name: JSON.stringify(this.user.users),
          years: this.timeFormat(this.years, 'YYYYMM', 'YYYY-MM')
        })
        this.$message.success('修改成功')
        this.user = this.$options.data().user
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.birthday-user-list {
  padding: 20px;

  .pagination {
    display: flex;
    justify-content: end;
  }
}

.field {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
  .title {
    font-weight: bold;
  }
}

::v-deep(.el-card) {
  border: none;
}
</style>
